home *** CD-ROM | disk | FTP | other *** search
/ Revista CD Expert 8 / Revista CD Expert nº 08 CD1.iso / Utilitarios / Programacao / Pacific C for DOS / EXAMPLES / FCALC.C < prev    next >
C/C++ Source or Header  |  1995-03-08  |  2KB  |  105 lines

  1. /*     Test program - this is a single-precision floating point
  2.  *    calculator. Type in expressions of the form A op B, where A and B
  3.  *    are floating point numbers, and op is an operator. The usual
  4.  *    arithmetic operators are recognized, plus = for comparision,
  5.  *    s for sine, c for cosine and t for tan. With c, s and t only the
  6.  *    first number need be given, e.g. 30 s will give the answer 0.50000.
  7.  *
  8.  *    To compile use PPD with "Use floating point library" enabled,
  9.  *    or use PACC FCALC.C -LF
  10.  */
  11.  
  12. #include    <ctype.h>
  13. #include    <math.h>
  14. #include    <stdlib.h>
  15. #include    <stdio.h>
  16. #include    <conio.h>
  17.  
  18. float    expr(void);
  19.  
  20. float    pi;
  21.  
  22. main()
  23. {
  24.     float    res;
  25.  
  26.     printf("\nPacific C Compiler calculator, enter a blank line to quit\n");
  27.     pi = 4 * atan(1);
  28.     for(;;) {
  29.         res = expr();
  30.         printf("Result = %f\n", res);
  31.     }
  32. }
  33.  
  34. float
  35. expr()
  36. {
  37.     float    a, b;
  38.     char *    cp;
  39.     char    c;
  40.     char    abuf[20];
  41.  
  42.     printf("FCALC> ");
  43.     gets(abuf);
  44.     if (!abuf[0])
  45.         exit(0);
  46.     cp = abuf;
  47.     while(isspace(*cp))
  48.         cp++;
  49.     a = atof(cp);
  50.     if(*cp == '-')
  51.         cp++;
  52.     while(isdigit(*cp) || *cp == 'e' || *cp == 'E' || *cp == '.')
  53.         cp++;
  54.     while(isspace(*cp))
  55.         cp++;
  56.     c = *cp;
  57.     if(c == 0) {
  58.         return a;
  59.     }
  60.     cp++;
  61.     while(isspace(*cp))
  62.         cp++;
  63.     b = atof(cp);
  64.     switch(c) {
  65.  
  66.     case 'c':
  67.         return cos(a / 180.0 * pi);
  68.  
  69.     case 's':
  70.         return sin(a / 180.0 * pi);
  71.  
  72.     case 't':
  73.         return tan(a / 180.0 * pi);
  74.  
  75.     case '+':
  76.         return a + b;
  77.  
  78.     case '-':
  79.         return a - b;
  80.  
  81.     case '*':
  82.         return a * b;
  83.  
  84.     case '/':
  85.         return a / b;
  86.  
  87.     case '=':
  88.         if(a < b)
  89.             printf(" < ");
  90.         if(a == b)
  91.             printf(" == ");
  92.         if(a > b)
  93.             printf(" > ");
  94.         if(a >= b)
  95.             printf(" >= ");
  96.         if(a <= b)
  97.             printf(" <= ");
  98.         putch('\n');
  99.         return 0;
  100.  
  101.     default:
  102.         return 0;
  103.     }
  104. }
  105.